﻿using DevComponents.AdvTree;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MachineBuildingSystem
{
    public partial class UserMgr : XtraForm
    {
        private string m_CurrentUser = "";
        public string CurrentUser
        {
            set { m_CurrentUser = value; }
        }
        private string m_Password = "";
        public string Password
        {
            set { m_Password = value; }
        }

        private Dictionary<long, List<long>> m_Dic = new Dictionary<long, List<long>>();

        public UserMgr()
        {
            InitializeComponent();
        }

        private void UserMgr_Load(object sender, EventArgs e)
        {
            RefreshUserTree();
            RefreshRoleTree();
        }

        private void btnSycnUser_Click(object sender, EventArgs e)
        {
            List<UserData> list = DataHelper.GetSyncUserData(m_CurrentUser, m_Password);
            if (list == null || list.Count == 0)
                return;
            if (!UpdateUser(list))
            {
                MessageBox.Show(this, "同步用户失败");
                return;
            }
            MessageBox.Show(this, "同步用户成功");
            RefreshUserTree();
        }

        private void RefreshUserTree()
        {
            DataTable dt = RefreshUserData();
            if (dt == null || dt.Rows.Count == 0)
                return;
            rootUserNode.Nodes.Clear();
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Node node = new Node();
                    node.CheckBoxVisible = true;
                    node.CheckState = CheckState.Unchecked;
                    node.Text = dr["USERNAME"].ToString() + "(" + dr["EMP_NAME"].ToString() + ")";
                    node.Tag = long.Parse(dr["ID"].ToString());
                    rootUserNode.Nodes.Add(node);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("加载用户树节点异常：" + ex.Message);
                MessageBox.Show("加载用户树节点异常：" + ex.Message);
            }
        }

        private void RefreshRoleTree()
        {
            DataTable dt = RefreshRoleData();
            if (dt == null || dt.Rows.Count == 0)
                return;
            rootRoleNode.Nodes.Clear();
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Node node = new Node();
                    node.CheckBoxVisible = true;
                    node.CheckState = CheckState.Unchecked;
                    node.Text = dr["names"].ToString();
                    node.Tag = long.Parse(dr["id"].ToString());
                    rootRoleNode.Nodes.Add(node);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("加载角色树节点异常：" + ex.Message);
                MessageBox.Show("加载角色树节点异常：" + ex.Message);
            }
        }

        private DataTable RefreshRoleData()
        {
            DataTable dt = new DataTable();
            try
            {
                string sql = "select * from HS_SECU_ROLE order by ID";
                dt = DB2Helper.CreateInstance().DoDB2Select(sql);
            }
            catch (Exception ex)
            {
                LogHelper.error("刷新角色信息异常：" + ex.Message);
                MessageBox.Show("刷新角色信息异常：" + ex.Message);
                return null;
            }
            return dt;
        }

        //刷新列表操作
        private DataTable RefreshUserData()
        {
            DataTable dt = new DataTable();
            try
            {
                string sql = "select * from HS_SECU_USER order by ID";
                dt = DB2Helper.CreateInstance().DoDB2Select(sql);
            }
            catch (Exception ex)
            {
                LogHelper.error("刷新用户信息异常：" + ex.Message);
                MessageBox.Show("刷新用户信息异常：" + ex.Message);
                return null;
            }
            return dt;
        }

        private DataTable RefreshUserRoleData(long userId)
        {
            DataTable dt = new DataTable();
            try
            {
                string sql = "select * from HS_SECU_ROLE_USER where USER_ID = " + userId;
                dt = DB2Helper.CreateInstance().DoDB2Select(sql);
            }
            catch (Exception ex)
            {
                LogHelper.error("刷新用户角色信息异常：" + ex.Message);
                MessageBox.Show("刷新用户角色信息异常：" + ex.Message);
                return null;
            }
            return dt;
        }
        private bool UpdateUser(List<UserData> list)
        {
            List<Dictionary<string, object>> syncResultList = new List<Dictionary<string, object>>();
            if (!DB2Helper.CreateInstance().DoDB2ExecuteBySync(list, out syncResultList))
                return false;
            //返回同步结果
            try
            {
                if (syncResultList == null || syncResultList.Count == 0)
                    return false;

                CGlobal.strSwapJsonData = JsonConvert.SerializeObject(syncResultList);
                bool isSuccess = DataHelper.SyncResult(m_CurrentUser, m_Password);
                if (!isSuccess)
                    return false;
            }
            catch (Exception ex)
            {
                LogHelper.error("同步用户后返回同步结果异常：" + ex.Message);
                return false;
            }
            return true;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            m_Dic.Clear();
            foreach (Node user in rootUserNode.Nodes)
            {
                if (user.CheckState == CheckState.Checked)
                {
                    List<long> roleIdList = new List<long>();
                    foreach (Node role in rootRoleNode.Nodes)
                    {
                        if (role.CheckState == CheckState.Checked)
                            roleIdList.Add(long.Parse(role.Tag.ToString()));
                    }
                    m_Dic.Add(long.Parse(user.Tag.ToString()), roleIdList);
                }
            }
            if (m_Dic.Count == 0)
                return;
            try
            {
                List<string> list = new List<string>();
                foreach (long userId in m_Dic.Keys)
                {
                    list.Add("delete from HS_SECU_ROLE_USER where User_id = " + userId);
                    foreach (long roleId in m_Dic[userId])
                        list.Add("insert into HS_SECU_ROLE_USER (ROLE_ID, USER_ID) values (" + roleId + "," + userId + ")");
                }
                if (!DB2Helper.CreateInstance().DoDB2Execute(list.ToArray()))
                {
                    MessageBox.Show(this, "保存失败");
                    return;
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("保存用户角色异常：" + ex.Message);
                MessageBox.Show("保存用户角色异常：" + ex.Message);
                return;
            }
            MessageBox.Show("保存成功！");
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void advTreeUser_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e)
        {
            Node selectedNode = advTreeUser.SelectedNode;
            if (selectedNode == null || selectedNode == rootUserNode)
            {
                foreach (Node child in rootUserNode.Nodes)
                    child.Checked = false;
                return;
            }
            long userId = long.Parse(selectedNode.Tag.ToString());
            //根据roleID获取勾选的操作
            DataTable dt = RefreshUserRoleData(userId);
            if (dt == null || dt.Rows.Count == 0)
            {
                foreach (Node child in rootRoleNode.Nodes)
                    child.Checked = false;
                return;
            }
            List<long> list = new List<long>();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(long.Parse(dr["Role_Id"].ToString()));
            }
            foreach (Node child in rootRoleNode.Nodes)
            {
                if (list.Contains(long.Parse(child.Tag.ToString())))
                    child.CheckState = CheckState.Checked;
                else
                    child.CheckState = CheckState.Unchecked;
            }
        }

        private void advTreeUser_NodeClick(object sender, TreeNodeMouseEventArgs e)
        {
            //如果根节点打钩，下面的子节点都打钩
            if (e.Node == rootUserNode)
            {
                if (e.Node.CheckState == CheckState.Checked)
                {
                    foreach (Node child in rootUserNode.Nodes)
                    {
                        child.CheckState = CheckState.Checked;
                    }
                }
                else if (e.Node.CheckState == CheckState.Unchecked)
                {
                    foreach (Node child in rootUserNode.Nodes)
                    {
                        child.CheckState = CheckState.Unchecked;
                    }
                }
            }
            else
            {
                int sum = 0;
                foreach (Node child in rootUserNode.Nodes)
                {
                    if (child.CheckState == CheckState.Checked)
                        sum++;
                }
                if (sum == rootUserNode.Nodes.Count)
                    rootUserNode.CheckState = CheckState.Checked;
                else if (sum == 0)
                    rootUserNode.CheckState = CheckState.Unchecked;
                else
                    rootUserNode.CheckState = CheckState.Indeterminate;
            }
        }

        private void advTreeRole_NodeClick(object sender, TreeNodeMouseEventArgs e)
        {
            //如果根节点打钩，下面的子节点都打钩
            if (e.Node == rootRoleNode)
            {
                if (e.Node.CheckState == CheckState.Checked)
                {
                    foreach (Node child in rootRoleNode.Nodes)
                    {
                        child.CheckState = CheckState.Checked;
                    }
                }
                else if (e.Node.CheckState == CheckState.Unchecked)
                {
                    foreach (Node child in rootRoleNode.Nodes)
                    {
                        child.CheckState = CheckState.Unchecked;
                    }
                }
            }
            else
            {
                int sum = 0;
                foreach (Node child in rootRoleNode.Nodes)
                {
                    if (child.CheckState == CheckState.Checked)
                        sum++;
                }
                if (sum == rootRoleNode.Nodes.Count)
                    rootRoleNode.CheckState = CheckState.Checked;
                else if (sum == 0)
                    rootRoleNode.CheckState = CheckState.Unchecked;
                else
                    rootRoleNode.CheckState = CheckState.Indeterminate;
            }
        }
    }
}
